package memorphic.slide.plugin.wizards;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Properties;

import org.eclipse.ant.core.AntRunner;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

public class CreateSlideViewWizard extends Wizard implements INewWizard {
	public CreateSlideView page;
	
	private ISelection selection;
	private IProject project; 
	
	/**
	 * Constructor for CreateSlideView
	 */
	public CreateSlideViewWizard() {
		super();
		setNeedsProgressMonitor(true);
	}
	
	/**
	 * Adding the page to the wizard
	 */
	public void addPages() {
		page = new CreateSlideView(selection);
		page.project = project;
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	@Override
	public boolean performFinish() {
		final String viewName = page.getViewName();
		final String viewPackage = page.getViewPackage();
		final String viewPackageDirectory = page.getSourceDirectory() + "/" + page.getViewPackage().replace(".", "/");
		final String delegateName = page.getDelegateName();
		final String delegatePackage = page.getDelegatePackage();
		final String delegatePackageDirectory = page.getSourceDirectory() + "/" + page.getDelegatePackage().replace(".", "/");
		final String baseViewName = page.getBaseViewName();
		final String packageID = page.getPackage();
		String temp = page.getIAppProps();
		temp= temp.replaceFirst(".as", "");
		final String iAppProps = temp;
		final Boolean createDelegate = page.getCreateDelegate();
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doFinish(viewName,
							viewPackage,
							viewPackageDirectory, 
							delegateName,
							delegatePackage,
							delegatePackageDirectory,
							iAppProps,
							baseViewName,
							packageID,
							createDelegate,
							monitor);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * The worker method. It will find the container, create the
	 * files, and refresh the workspace.
	 */
	private void doFinish(
			String viewName,
			String viewPackage,
			String viewPackageDirectory,
			String delegateName,
			String delegatePackage,
			String delegatePackageDirectory,
			String iAppProps,
			String baseViewName,
			String packageID,
			Boolean createDelegate,
		IProgressMonitor monitor)
		throws CoreException {
		final Properties props = new Properties();
		props.put("viewName", viewName);
		props.put("viewPackage", viewPackage);
		props.put("viewPackageDirectory", viewPackageDirectory);
		props.put("delegateName", delegateName);
		props.put("delegatePackage", delegatePackage);
		props.put("delegatePackageDirectory", delegatePackageDirectory);
		props.put("iAppProps", iAppProps);
		props.put("baseView", baseViewName);
		props.put("packageID", packageID);
		try
		{
			URL fileURL = FileLocator.toFileURL(Platform.getBundle("memorphic.slide.plugin").getEntry("/resources/slide-project-setup.xml"));
			
			AntRunner runner = new AntRunner();
			String path = fileURL.getPath();
			System.out.println(path);
			runner.setBuildFileLocation(path);
			runner.addUserProperties(props);
			String target;
			if (createDelegate)
				target = "createViewWithDelegate";
			else
				target = "createView";
			String[] targets = {target};
			runner.setExecutionTargets(targets);
			runner.run(monitor);
		}
		catch (IOException e)
		{
			System.out.println("ant failed: " + e.getCause().getMessage());
			throw new CoreException(Status.CANCEL_STATUS);
		}
		
		editSlideProjectFile(project, props);
		
		ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, monitor);
	}

	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
		if (selection.size() > 1)
			return;
		Object obj = selection.getFirstElement();
		if (obj instanceof IResource) {
			IContainer container;
			if (obj instanceof IContainer)
				container = (IContainer) obj;
			else
				container = ((IResource) obj).getParent();
			IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
			while (true) {
				String nameStr = container.getName().toString();
				for (int i = 0; i < projects.length; i++)
				{
					if (nameStr.equals(projects[i].getName()))
					{
						project = projects[i];
						break;
					}
				}
				container = container.getParent();
				if (container.equals(ResourcesPlugin.getWorkspace().getRoot()))
					break;
			}
		}
	}

	private void editSlideProjectFile(IProject project, Properties props) {
		
	}

}
